import 'dart:convert';

import 'package:FineArt/components/CustomDialog.dart';
import 'package:FineArt/components/azlist/az_common.dart';
import 'package:FineArt/components/azlist/az_listview.dart';
import 'package:FineArt/components/azlist/index_bar.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/imageview/RoundCheckBox.dart';
import 'package:FineArt/page/imageview/RoundCheckBox1.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:FineArt/core/utils/event.dart';
class ContactListPage extends StatefulWidget {
  ///0 添加 1 移除 2转让班主任
  int type;
  TeacherClassesEntity classesEntity;
  List<Student> studentList;
  ContactListPage({this.type, this.classesEntity,this.studentList});

  @override
  State<StatefulWidget> createState() {
    return new _ContactListPageState();
  }
}

class _ContactListPageState extends State<ContactListPage> {
  List<ContactInfoLocal> _contactsLocal = [];
  List<ContactInfo> _contacts = [];
  double susItemHeight = 20;
  List<Student> studentList;
  @override
  void initState() {
    super.initState();
    //移除人员
    loadData();
    if(widget.type==0) {
      _loadUnSelectStudent();
    }
  }

  _loadUnSelectStudent() {
    // int postId = (SPUtils.getRole() == "teacher") ? 1 : 2;
    int status = int.parse(widget.classesEntity.status);
    ClassApi().unSelectStudent(1, 2, 1003).then((res) {
      if (res.code == 200) {
        if(res.data.list.length==0) return;
        setState(() {
          // _contacts = res.data.list;
          for(int i=0;i<res.data.list.length;i++){
            ContactInfo info = res.data.list[i];
            info.isCheck=false;
            _contacts.add(info);
          }
          _handleList(_contacts);
        });
      } else {
        ToastUtils.toast("获取人员出错${res.msg}");
      }
    });
  }



  void loadData() async {
    if(widget.studentList!=null){
      studentList=widget.studentList;
      for(int i=0;i<studentList.length;i++){
        if(studentList[i].uid<0) continue;
        ContactInfo info = new ContactInfo();
        info.name = studentList[i].name;
        info.isCheck=false;
        info.uid=studentList[i].uid;
        _contacts.add(info);
      }
      setState(() {
        _handleList(_contacts);
      });
    }else {
      // //加载联系人列表
      // rootBundle.loadString('assets/data/contacts.json').then((value) {
      //   List list = json.decode(value);
      //   list.forEach((v) {
      //     _contactsLocal.add(ContactInfoLocal.fromJson(v));
      //   });
      //   // _handleList(_contactsLocal);
      //   buildLocalData();
      // });
    }
  }

  void _handleList(List<ContactInfo> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(_contacts);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(_contacts);

    // add header.
    // _contacts.insert(0, ContactInfoLocal(name: 'header', tagIndex: '↑'));
  }

  buildLocalData() {
    setState(() {
      for (int i = 0; i < _contactsLocal.length; i++) {
        ContactInfo info = new ContactInfo();
        info.name = _contactsLocal[i].name;
        info.isCheck=false;
        _contacts.add(info);
      }
      _handleList(_contacts);
    });
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.0),
      height: susItemHeight,
      width: double.infinity,
      color: bg_button_gray,
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Text(
            '$susTag',
            textScaleFactor: 1,
          ),
        ],
      ),
    );
  }

  Widget buildContactItem(ContactInfo model, int index) {
    String susTag = model.getSuspensionTag();
    return InkWell(
      child: Padding(
          padding: EdgeInsets.symmetric(
              vertical: getPortraitSHeight(0.5),
              horizontal: getPortraitSWidth(10)),
          child: Column(
            children: [
              Offstage(
                  offstage: model.isShowSuspension != true,
                  child: _buildSusWidget(susTag)),
              Row(
                children: [
                  RoundCheckBox1(
                  value: model.isCheck,
                  isRadio: true,
                  onChanged: (bool val) {
                    LogUtil.d("is Check $index $val");
                    setState(() {
                      _contacts[index].isCheck=val;
                    });

                  }),
                  Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: bg_icon_gray,
                      borderRadius: BorderRadius.all(Radius.circular(4.0)),
                    ),
                    child: model.portrait != null
                        ? Image.network(
                            model.portrait,
                            fit: BoxFit.cover,
                            // width: getPortraitSWidth(50),
                            // height: getPortraitSHeight(50),
                          )
                        : SizedBox(),
                    width: getPortraitSWidth(50),
                    height: getPortraitSHeight(50),
                  ),
                  SizedBox(
                    width: getPortraitSWidth(12.5),
                  ),
                  Text(
                    model.name,
                    style: TextStyle(fontSize: setSp(15), color: text_black),
                  ),
                  // Expanded(child: Text("")),
                ],
              ),
            ],
          )),
      onTap: () {
        LogUtil.d("class click $index");
        setState(() {
          _contacts[index].isCheck=!_contacts[index].isCheck;
        });
      },
    );
  }

  Widget _buildListItem(ContactInfoLocal model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.blue[700],
            child: Text(
              model.name[0],
              style: TextStyle(color: Colors.white),
            ),
          ),
          title: Text(model.name),
          onTap: () {
            print("OnItemClick: $model");
            Navigator.pop(context, model);
          },
        )
      ],
    );
  }

  Decoration getIndexBarDecoration(Color color) {
    return BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(0.0),
        border: Border.all(color: Colors.grey[300], width: .5));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text(
              "选择联系人",
              style: TextStyle(color: text_black, fontSize: setSp(18)),
            ),
            centerTitle: true,
            elevation: 0,
            backgroundColor: Colors.white,
            brightness: Brightness.light,
            toolbarHeight: getPortraitSHeight(50),
            actions: [getAppBarRightActionItem()],
            leading: IconButton(
                alignment: Alignment.centerLeft,
                icon: Image.asset(
                  "assets/images/icon_back_black.png",
                  width: getPortraitSWidth(11),
                  height: getPortraitSHeight(18),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                })),
        body: Padding(
          padding: EdgeInsets.only(
            top: 10,
          ),
          child: AzListView(
            data: _contacts,
            itemCount: _contacts.length,
            itemBuilder: (BuildContext context, int index) {
              // if (index == 0) return _buildHeader();
              ContactInfo model = _contacts[index];
              // return _buildListItem(model);
              return buildContactItem(model, index);
            },
            physics: BouncingScrollPhysics(),
            // indexBarData: SuspensionUtil.getTagIndexList(_contacts),//右侧字母可以只显示匹配到的字母
            indexHintBuilder: (context, hint) {
              //中间显示的文字
              return Container(
                alignment: Alignment.center,
                width: 60.0,
                height: 60.0,
                decoration: BoxDecoration(
                  color: Colors.blue[700].withAlpha(200),
                  shape: BoxShape.circle,
                ),
                child: Text(hint,
                    style: TextStyle(color: Colors.white, fontSize: 30.0)),
              );
            },
            indexBarMargin: EdgeInsets.all(10),
            indexBarOptions: IndexBarOptions(
              needRebuild: true,
              // decoration: getIndexBarDecoration(Colors.grey[50]),
              // downDecoration: getIndexBarDecoration(Colors.grey[200]),
            ),
          ),
        ));
  }
  Widget getAppBarRightActionItem() {
    return InkWell(
      child: Padding(
          padding: EdgeInsets.only(top: getPortraitSHeight(14), right: 10),
          child: Text(
            "确定",
            style: TextStyle(fontSize: setSp(16), color: text_black),
          )),
      onTap: () {
        LogUtil.d("confirm click>>>>>>>>>>>>>>>>>>>>");
        setState(() {
           if(widget.type==1){
             deleteConfirm();
           }
           else{
             addStudentConfirm();
           }
        });
      },
    );
  }
  List<String>  _getSelectIds(){
    List<String> ids=[];
    for(int i=0;i<_contacts.length;i++){
      if(_contacts[i].isCheck){
        String uid = _contacts[i].uid==null?_contacts[i].userId:_contacts[i].uid.toString();
        ids.add(uid.toString());
      }
    }
    return ids;
  }
  void deleteConfirm() {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: "确认要移除当前选中成员吗?",
              enterTxt: "确认",
              callback: (res0) {
                LogUtil.d("customerDialog Sure>>>>>>>>>>>>>>>>>");
                List<String> ids=_getSelectIds();
                StudentDelRequestBody body= StudentDelRequestBody(ids, widget.classesEntity.classId);
                 ClassApi().removeClassStudent(body).then((result) {
                   if (result.code == 200) {
                     ToastUtils.toast("移除成功");
                     Navigator.pop(context);
                     XEvent.post("refreshClassDetail","remove");
                   }
                   else{
                     ToastUtils.toast("移除出错${result.msg}");
                   }
                 });
              }
          );
        }
    );

  }
  void addStudentConfirm() {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: "确认要添加当前选中成员吗?",
              enterTxt: "确认",
              callback: (res0) {
                List<String> ids=_getSelectIds();
                LogUtil.d(ids);
                StudentDelRequestBody body = StudentDelRequestBody(
                    ids, widget.classesEntity.classId);
                ClassApi().addClassStudent(body).then((result) {
                  if (result.code == 200) {
                    ToastUtils.toast("添加成功");
                    Navigator.pop(context);
                    XEvent.post("refreshClassDetail","add");
                  }
                  else{
                    ToastUtils.toast("添加出错${result.msg}");
                  }
                });
              }
          );
        }
    );
  }
}

class ContactInfoLocal extends ISuspensionBean {
  String name;
  String tagIndex;
  String namePinyin;

  Color bgColor;
  IconData iconData;

  String img;
  String id;
  String firstletter;

  ContactInfoLocal({
    this.name,
    this.tagIndex,
    this.namePinyin,
    this.bgColor,
    this.iconData,
    this.img,
    this.id,
    this.firstletter,
  });

  ContactInfoLocal.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        img = json['img'],
        id = json['id']?.toString(),
        firstletter = json['firstletter'];

  Map<String, dynamic> toJson() => {
//        'id': id,
        'name': name,
        'img': img,
//        'firstletter': firstletter,
//        'tagIndex': tagIndex,
//        'namePinyin': namePinyin,
//        'isShowSuspension': isShowSuspension
      };

  @override
  String getSuspensionTag() => tagIndex;

  @override
  String toString() => json.encode(this);
}
